Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
I am getting "undefined" while adding charcters in my array in javascript

Here is my code can someone just explain why I am getting undefined?? I have split the words and then reverse them and after reversing I tried to store them in a different array. Thank you

const text = document.querySelector("#text");
const reverseText = document.querySelector("#reverseText");

let words = text.innerHTML.split("").reverse();
console.log(words);
let reversedWords = [];
let counter = 0;
for (var i = 0; i <= words.length - 1; i++) {
  if (words[i] != " ") {
    reversedWords[counter] += words[i];
  } else {
    counter++;
  }
}
console.log(reversedWords);
<p id="text">hello nixit</p>
<p id="reverseText"></p>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your issue is that the first time you try and access reversedWords[counter], it is undefined because you've initialised reversedWords to be an empty array.

Without changing much of your code (because you said you're doing it this way as a challenge), you could try initialising reversedWords to have the appropriate number of elements, initialised to empty strings

const content = text.textContent;
const words = content.split("").reverse();
const reversedWords = Array.from({ length: content.split(" ").length }, () => "");
about 4 years ago · Juan Pablo Isaza Relatório

0

You're using an array so you need to push things into it, and then join it up into a new string once the iteration is done.

const text = document.querySelector('#text');
const reverseText = document.querySelector('#reverseText');

function reverse(str) {

  // `split` the string on the spaces
  const words = str.split(' ');

  const reversedWords = [];

  for (let i = 0; i < words.length; i++) {

    // For each word split, reverse, and then rejoin it
    const word = words[i].split('').reverse().join('');

    // And then add the word to the array
    reversedWords.unshift(word);
  }

  // Return the completed array
  return reversedWords;
}

const str = text.textContent;
reverseText.textContent = JSON.stringify(reverse(str));
<p id="text">hello nixit</p>
<p id="reverseText"></p>

Additional documentation

  • unshift
about 4 years ago · Juan Pablo Isaza Relatório

0

I suggest using a string instead of an array. Then you can split it to turn it into an array.

const reversedChars = 'hello nixit'.split("").reverse()

const reversedWords = ''

reversedChars.forEach(char => {
    reversedWords += char
})

const reversedWordsArray =  reversedWords.split(' ')

console.log(reversedWords)
// Output: tixin olleh
console.log(reversedWordsArray)
// Output: [ 'tixin', 'olleh' ]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda